from django import forms
from django.core.exceptions import ValidationError
from phone_info_app import models
from phone_info_app.utils.BootstrapModelForm import BootstrapModelForm, BootstrapForm
from phone_info_app.utils.encrypt import md5

# 手机信息
class PhoneModelForm(BootstrapModelForm):
    class Meta:
        model = models.AllPhones
        fields = '__all__'

# 用户注册
class AdminModelForm(BootstrapModelForm):
    # render_value=True  保证刷新界面，数据不会被清走
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ["username", "password", "confirm_password"]
        # fields = '__all__'

        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    # 钩子函数，中间人，把数据拉出来，做完事后return回去
    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if pwd != confirm:
            raise ValidationError("密码不一致")
        return confirm

# 登录验证
class LoginForm(BootstrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

# 登录验证(有验证码)
class VerityForm(BootstrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

# 密码重置
class ResetForm(BootstrapModelForm):
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=False))

    class Meta:
        model = models.Admin
        fields = ["password", "confirm_password"]
        # fields = '__all__'

        widgets = {
            "password": forms.PasswordInput(render_value=False)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    # 钩子函数，中间人，把数据拉出来，做完事后return回去
    def clean_confirm_password(self):
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if pwd != confirm:
            raise ValidationError("密码不一致")
        return confirm